<template>
  <y-dialog @close="emit('close')" width="800px" append-to-body>
    <el-form
      ref="importExportRef"
      :model="form"
      :rules="rules"
      size="default"
      label-width="120px"
    >
      <el-row>
        <el-col>
          <el-form-item :label="labelPath" prop="path">
            <el-input
              v-model="form.path"
              :placeholder="'请输入有效的' + labelPath"
              clearable
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="emit('close')">取消</el-button>
      </div>
    </template>
  </y-dialog>
</template>

<script setup>
import { importScript, exportScript } from "@/api/tms/testcase";

const { proxy } = getCurrentInstance();

const emit = defineEmits(["submited", "close"]);

const props = defineProps({
  operate: { type: String, default: "import" },
  product: { type: String, default: undefined },
  module: { type: String, default: undefined },
});

const labelPath = computed(() => {
  return props.operate === "import" ? "导入路径" : "导出路径";
});

const data = reactive({
  form: {
    path: "",
  },
  queryParams: {
    product: undefined,
    module: undefined,
    path: undefined,
  },
  rules: {
    path: [
      {
        required: true,
        pattern: /^[a-zA-Z]:\\(?:[^\\\/:*?"<>|\r\n]+\\)*[^\\\/:*?"<>|\r\n]*$/,
        message: "请输入有效的导出路径",
        trigger: "blur",
      },
    ],
  },
});

const { form, queryParams, rules } = toRefs(data);

/** 提交按钮事件 */
function submit() {
  proxy.$refs["importExportRef"].validate((valid) => {
    if (valid) {
      queryParams.value.path = form.value.path;
      queryParams.value.product = props.product;
      queryParams.value.module = props.module;
      if (props.operate === "import") {
        importScript(queryParams.value).then((res) => {
          proxy.$modal.msgSuccess("导入成功");
        });
      } else {
        exportScript(queryParams.value).then((res) => {
          proxy.$modal.msgSuccess("导出成功");
        });
      }
      emit("close");
    }
  });
}
</script>
